<?php

namespace App\Services;

use Guzzle\Http\Exception\RequestException;

class UniPush{

    private $host;
    private $app_id;
    private $app_key;
    private $master_secret;

    const TRANSMISSION_TEMPLATE = 1;          //透传功能模板
    const LINK_TEMPLATE = 2;                  //通知打开链接模板
    const NOTIFICATION_TEMPLATE = 3;          //通知透传模板
    const NOTIFICATION_DOWNLOAD_TEMPLATE = 4; //通知弹框下载模板

    public function __construct()
    {
        $this->host = env('IGT_HOST');
        $this->app_id = env('IGT_APP_ID');
        $this->app_key = env('IGT_APP_KEY');
        $this->master_secret = env('IGT_MASTER_SECRET');
    }

    /**
     * 绑定别名
     * */
    public function bindAlias($alias,$clientId) {
        $igt = new \IGeTui($this->host, $this->app_key, $this->master_secret);
        $ret = $igt->bindAlias($this->app_id,$alias,$clientId);
        return $ret;
    }

    /**
     * 解绑别名
     * */
    public function unBindAlias($alias,$clientId) {
        $igt = new \IGeTui($this->host, $this->app_key, $this->master_secret);
        $ret = $igt->unBindAlias($this->app_id,$alias,$clientId);
        return $ret;
    }

    /**
     * 批量绑定别名
     * */
    public function bindAliasBatch($targetList) {
        $igt = new \IGeTui($this->host, $this->app_key, $this->master_secret);
//        $targetList = [];
//        $targetList['clientId'] = '';
//        $targetList['alias'] = '';
        $ret = $igt->bindAliasBatch($this->app_id,$targetList);
        return $ret;
    }

    /**
     * 根据别名查询cid
     * */
    public function queryClientId($alias) {
        $igt = new \IGeTui($this->host, $this->app_key, $this->master_secret);
        $ret = $igt->queryClientId($this->app_id,$alias);
        return $ret;
    }

    /**
     * 根据cid查询别名
     * */
    public function queryAlias($clientId) {
        $igt = new \IGeTui($this->host, $this->app_key, $this->master_secret);
        $ret = $igt->queryAlias($this->app_id,$clientId);
        return $ret;
    }


    /**
     * 移除黑名单用户
     * */
    public function restoreCidListFromBlkDemo($cidList){
        $igt = new \IGeTui($this->host,$this->app_key,$this->master_secret);
        $ret = $igt->restoreCidListFromBlk($this->app_id,$cidList);
        return $ret;
    }
    /**
     * 添加黑名单用户
     * */
    public function addCidListToBlkDemo($cidList){
        $igt = new \IGeTui($this->host,$this->app_key,$this->master_secret);
        $ret = $igt->addCidListToBlk($this->app_id,$cidList);
        return $ret;
    }

    /**
     * 根据cid查询手机号
     * */
    public function queryCidPnDemo($cidList){
        $igt = new \IGeTui($this->host,$this->app_key,$this->master_secret);
        $ret = $igt->queryCidPn($this->app_id,$cidList);
        return $ret;
    }

    /**
     * 获取用户状态
     * @param string $clientId
     * @return mixed
     * */
    public function getUserStatus($clientId) {
        $igt = new \IGeTui($this->host,$this->app_key,$this->master_secret);
        $rep = $igt->getClientIdStatus($this->app_id,$clientId);
        return $rep;
    }

    //推送任务停止
    public function stoptask(){
        $igt = new \IGeTui($this->host,$this->app_key,$this->master_secret);
        $igt->stop("");
    }

    //通过服务端设置ClientId的标签  为用户绑定标签
    public function setTag($clientId,$tagList){
        $igt = new \IGeTui($this->host,$this->app_key,$this->master_secret);
        $rep = $igt->setClientTag($this->app_id,$clientId,$tagList);
        return $rep;
    }

    /**
     * 查询用户标签
     * */
    public function getUserTags($clientId) {
        $igt = new \IGeTui($this->host,$this->app_key,$this->master_secret);
        $rep = $igt->getUserTags($this->app_id,$clientId);
        //$rep.connect();
        return $rep;
    }

    //pushMessageToSingleToSMS();
    //setSmsInfo接口
    public function pushMessageToSingleToSMS(){
        $igt = new \IGeTui($this->host,$this->app_key,$this->master_secret);
        $template = new \IGtTransmissionTemplate();
        $template->set_appId($this->app_id);
        $template->set_appkey($this->app_key);
        $template->set_transmissionType(2);
        $template->set_transmissionContent("123123");

        $smsMessage = new \SmsMessage();
//    $smsContent = array();
//    $smsContent["url"] = "http://www.baidu.com/getui";
        $smsMessage->setPayload("1234");
        $smsMessage->setUrl("http://www/getui");
        $smsMessage->setSmsTemplateId("");
        $smsMessage->setOfflineSendtime(1000);
        $smsMessage->setIsApplink(true);
//    $smsMessage->smsContent($smsContent);
        $template->setSmsInfo($smsMessage);

        $message = new \IGtSingleMessage();
        $message->set_isOffline(true);
        $message->set_offlineExpireTime(60*60*1000);
        $message->set_data($template);
        $target = new \IGtTarget();
        $target ->set_appId($this->app_id);
        $target ->set_clientId(CID);
        try {
            for ($i = 0; $i < 1; $i++) {
                $ret = $igt->pushMessageToSingle($message, $target, "121231233123");
                return $ret;
            }
        }catch (RequestException $e){
            $requstId = $e->getRequestId();
            $ret = $igt->pushMessageToSingle($message,$target,$requstId);
            return $ret;
        }
    }

    //服务端推送接口，支持三个接口推送
    //1.PushMessageToSingle接口：支持对单个用户进行推送
    //2.PushMessageToList接口：支持对多个用户进行推送，建议为50个用户
    //3.pushMessageToApp接口：对单个应用下的所有用户进行推送，可根据省份，标签，机型过滤推送
    //
    /**
     * 单推接口
     * @param string $title
     * @param string $content
     * @param int $templateId
     * @param string $clientId
     * @return mixed
     * */
    public function pushMessageToOne(string $title,string $content,int $templateId,string $clientId){

        $igt = new \IGeTui($this->host,$this->app_key,$this->master_secret);

        //消息模版
        switch ($templateId){
            case self::TRANSMISSION_TEMPLATE:
                // 1.TransmissionTemplate:透传功能模板
                $template = $this->IGtTransmissionTemplateDemo($title,$content);
                break;
            case self::LINK_TEMPLATE:
                // 2.LinkTemplate:通知打开链接功能模板
                $template = $this->IGtLinkTemplateDemo($title,$content);
                break;
            case self::NOTIFICATION_TEMPLATE:
                // 3.NotificationTemplate：通知透传功能模板
                $template = $this->IGtNotificationTemplateDemo($title,$content);
                break;
//            case self::NOTIFICATION_DOWNLOAD_TEMPLATE:
            // 4.NotyPopLoadTemplate：通知弹框下载功能模板
//                $template = $this->IGtNotyPopLoadTemplateDemo($title,$content);
//                break;
            default:
                $template = $this->IGtNotificationTemplateDemo($title,$content);
                break;
        }

        //个推信息体
        $message = new \IGtSingleMessage();

        $message->set_isOffline(true);//是否离线
        $message->set_offlineExpireTime(3600*12*1000);//离线时间
        $message->set_data($template);//设置推送消息类型
    	$message->set_PushNetWorkType(0);//设置是否根据WIFI推送消息，1为wifi推送，0为不限制推送
        //接收方
        $target = new \IGtTarget();
        $target->set_appId($this->app_id);
        $target->set_clientId($clientId);
    //    $target->set_alias(Alias);

        try {
            $rep = $igt->pushMessageToSingle($message, $target);
            return $rep;
        }catch(RequestException $e){
            $requstId =$e->getRequestId();
            $rep = $igt->pushMessageToSingle($message, $target,$requstId);
            return $rep;
        }

    }

    /**
     * 多个用户推送
     * */
    public function pushMessageToList($title,$content,$templateId,$userList)
    {
        putenv("gexin_pushList_needDetails=true");
        putenv("gexin_pushList_needAsync=true");

        $igt = new \IGeTui($this->host, $this->app_key, $this->master_secret);

        //消息模版
        switch ($templateId){
            case self::TRANSMISSION_TEMPLATE:
                // 1.TransmissionTemplate:透传功能模板
                $template = $this->IGtTransmissionTemplateDemo($title,$content);
                break;
            case self::LINK_TEMPLATE:
                // 2.LinkTemplate:通知打开链接功能模板
                $template = $this->IGtLinkTemplateDemo($title,$content);
                break;
            case self::NOTIFICATION_TEMPLATE:
                // 3.NotificationTemplate：通知透传功能模板
                $template = $this->IGtNotificationTemplateDemo($title,$content);
                break;
//            case self::NOTIFICATION_DOWNLOAD_TEMPLATE:
                  // 4.NotyPopLoadTemplate：通知弹框下载功能模板
//                $template = $this->IGtNotyPopLoadTemplateDemo($title,$content);
//                break;
            default:
                $template = $this->IGtNotificationTemplateDemo($title,$content);
                break;
        }

        //个推信息体
        $message = new \IGtListMessage();
        $message->set_isOffline(true);//是否离线
        $message->set_offlineExpireTime(3600 * 12 * 1000);//离线时间
        $message->set_data($template);//设置推送消息类型
        $message->set_PushNetWorkType(0);	//设置是否根据WIFI推送消息，1为wifi推送，0为不限制推送
        $contentId = $igt->getContentId($message);
//        $contentId = $igt->getContentId($message,"toList任务别名功能");	//根据TaskId设置组名，支持下划线，中文，英文，数字

        $targetList = [];
        foreach ($userList as $k=>$v){
            //接收方
            $target = new \IGtTarget();
            $target->set_appId($this->app_id);
            $target->set_clientId($v['client_id']);
//            $target1->set_alias($v['alias']);

            $targetList[] = $target;
        }

        $rep = $igt->pushMessageToList($contentId, $targetList);

        return $rep;
    }

    /**
     * 群推接口案例
     * */
    public function pushMessageToAll($title,$content,$templateId,$download_url=''){

        $igt = new \IGeTui($this->host,$this->app_key,$this->master_secret);

        //消息模版
        switch ($templateId){
            case self::TRANSMISSION_TEMPLATE:
                // 1.TransmissionTemplate:透传功能模板
                $template = $this->IGtTransmissionTemplateDemo($title,$content);
                break;
            case self::LINK_TEMPLATE:
                // 2.LinkTemplate:通知打开链接功能模板
                $template = $this->IGtLinkTemplateDemo($title,$content);
                break;
            case self::NOTIFICATION_TEMPLATE:
                // 3.NotificationTemplate：通知透传功能模板
                $template = $this->IGtNotificationTemplateDemo($title,$content);
                break;
            case self::NOTIFICATION_DOWNLOAD_TEMPLATE:
                // 4.NotyPopLoadTemplate：通知弹框下载功能模板
                $template = $this->IGtNotyPopLoadTemplateDemo($title,$content,$download_url);
                break;
            default:
                $template = $this->IGtNotificationTemplateDemo($title,$content);
                break;
        }

        //个推信息体
        //基于应用消息体
        $message = new \IGtAppMessage();
        $message->set_isOffline(true);
        $message->set_offlineExpireTime(10 * 60 * 1000);//离线时间单位为毫秒，例，两个小时离线为3600*1000*2
        $message->set_data($template);

        $appIdList=array($this->app_id);
        $message->set_appIdList($appIdList);

        //限制群推范围 手机类型，地区，标签
//        $phoneTypeList=array('ANDROID');
//        $provinceList=array('浙江');
//        $tagList=array('haha');
//        $age = array("0000", "0010");

//        $cdt = new \AppConditions();
//        $cdt->addCondition(\AppConditions::PHONE_TYPE, $phoneTypeList);
//        $cdt->addCondition(\AppConditions::REGION, $provinceList);
//        $cdt->addCondition(\AppConditions::TAG, $tagList);
//        $cdt->addCondition("age", $age);

//        $message->set_conditions($cdt);

        $rep = $igt->pushMessageToApp($message);

        return $rep;
    }


    /*
 * 批量单推 用于一次创建提交多个单推任务。
 * 业务自己实现
 * */
    public function pushMessageToSingleBatch()
    {
        putenv("gexin_pushSingleBatch_needAsync=false");

        $igt = new \IGeTui($this->host, $this->app_key, $this->master_secret);
        $batch = new \IGtBatch($this->app_key, $igt);
        $batch->setApiUrl($this->host);
        //$igt->connect();
        //消息模版：
        // 1.TransmissionTemplate:透传功能模板
        // 2.LinkTemplate:通知打开链接功能模板
        // 3.NotificationTemplate：通知透传功能模板
        // 4.NotyPopLoadTemplate：通知弹框下载功能模板

        //$template = IGtNotyPopLoadTemplateDemo();
        $templateLink = $this->IGtLinkTemplateDemo();
        $templateNoti = $this->IGtNotificationTemplateDemo();
        //$template = IGtTransmissionTemplateDemo();

        //个推信息体
        $messageLink = new \IGtSingleMessage();
        $messageLink->set_isOffline(true);//是否离线
        $messageLink->set_offlineExpireTime(12 * 1000 * 3600);//离线时间
        $messageLink->set_data($templateLink);//设置推送消息类型
        //$messageLink->set_PushNetWorkType(1);//设置是否根据WIFI推送消息，1为wifi推送，0为不限制推送

        $targetLink = new \IGtTarget();
        $targetLink->set_appId($this->app_id);
        $targetLink->set_clientId(CID1);
        $batch->add($messageLink, $targetLink);

        //个推信息体
        $messageNoti = new \IGtSingleMessage();
        $messageNoti->set_isOffline(true);//是否离线
        $messageNoti->set_offlineExpireTime(12 * 1000 * 3600);//离线时间
        $messageNoti->set_data($templateNoti);//设置推送消息类型
        //$messageNoti->set_PushNetWorkType(1);//设置是否根据WIFI推送消息，1为wifi推送，0为不限制推送

        $targetNoti = new \IGtTarget();
        $targetNoti->set_appId($this->app_id);
        $targetNoti->set_clientId(CID2);
        $batch->add($messageNoti, $targetNoti);
        try {
            $rep = $batch->submit();
        }catch(Exception $e){
            $rep = $batch->retry();
        }

        return $rep;

    }

    /**
     * 第三方厂商推送
     * */
    public function IGtTransmissionTemplateDemo($title,$content){
        $template =  new \IGtTransmissionTemplate();
        $template->set_appId($this->app_id);//应用appid
        $template->set_appkey($this->app_key);//应用appkey
        $template->set_transmissionType(1);//透传消息类型
        $template->set_transmissionContent("测试离线ddd");//透传内容
        //$template->set_duration(BEGINTIME,ENDTIME); //设置ANDROID客户端在此时间区间内展示消息
        //APN简单推送
//        $template = new IGtAPNTemplate();
//        $apn = new IGtAPNPayload();
//        $alertmsg=new SimpleAlertMsg();
//        $alertmsg->alertMsg="";
//        $apn->alertMsg=$alertmsg;
////        $apn->badge=2;
////        $apn->sound="";
//        $apn->add_customMsg("payload","payload");
//        $apn->contentAvailable=1;
//        $apn->category="ACTIONABLE";
//        $template->set_apnInfo($apn);
//        $message = new IGtSingleMessage();

        //第三方厂商推送透传消息带通知处理
        $notify = new \IGtNotify();
        $notify -> set_payload("{}");
        $notify -> set_title($title);
        $notify -> set_content($content);
        $notify->set_type(\NotifyInfo_Type::_payload);
        $template -> set3rdNotifyInfo($notify);

        //APN高级推送
        $apn = new \IGtAPNPayload();
        $alertmsg=new \DictionaryAlertMsg();
        $alertmsg->body="";
        $alertmsg->actionLocKey="";
        $alertmsg->locKey="";
        $alertmsg->locArgs=array("");
        $alertmsg->launchImage="";
//        IOS8.2 支持
        $alertmsg->title="";
        $alertmsg->titleLocKey="";
        $alertmsg->titleLocArgs=array("");

        $alertmsg->subtitle = "subtitle";

        $apn->alertMsg=$alertmsg;
        $apn->badge=7;
        $apn->sound="";
        $apn->add_customMsg("payload","");
        $apn->voicePlayType = 1;
        $apn->contentAvailable=1;
        $apn->category="ACTIONABLE";

        //IOS多媒体消息处理
        $media = new \IGtMultiMedia();
        $media -> set_url("");
        $media -> set_onlywifi(false);
        $media -> set_type(MediaType::pic);

        $medias = array();
        $medias[] = $media;
        //$apn->set_multiMedias($medias);

        $template->set_apnInfo($apn);

        //PushApn老方式传参
//    $template = new IGtAPNTemplate();
//          $template->set_pushInfo("", 10, "", "com.gexin.ios.silence", "", "", "", "");

        return $template;
    }

    /**
     * 通知链接模板方法
     * @param string $title
     * @param string $content
     * @param string $url
     * @param string $logo
     * @return mixed
     * */
    public function IGtLinkTemplateDemo($title,$content,$url="",$logo=""){
        $template =  new \IGtLinkTemplate();
        $template ->set_appId($this->app_id);//应用appid
        $template ->set_appkey($this->app_key);//应用appkey
        $template ->set_title($title);//通知栏标题
        $template ->set_text($content);//通知栏内容
        $template ->set_logo($logo);//通知栏logo
        $template ->set_isRing(true);//是否响铃
        $template ->set_isVibrate(true);//是否震动
        $template ->set_isClearable(true);//通知栏是否可清除
        $template ->set_url($url);//打开连接地址
        //$template->set_duration(BEGINTIME,ENDTIME); //设置ANDROID客户端在此时间区间内展示消息
        return $template;
    }

    /**
     * 透传模板
     * @param string $title
     * @param string $content
     * @return mixed
     * */
    public function IGtNotificationTemplateDemo($title,$content){
        $template =  new \IGtNotificationTemplate();
        $template->set_appId($this->app_id);//应用appid
        $template->set_appkey($this->app_key);//应用appkey
        $template->set_transmissionType(1);//透传消息类型
        $template->set_transmissionContent("测试离线");//透传内容
        $template->set_title($title);//通知栏标题
        $template->set_text($content);//通知栏内容
        $template->set_logo("");//通知栏logo
        $template->set_isRing(true);//是否响铃
        $template->set_isVibrate(true);//是否震动
        $template->set_isClearable(true);//通知栏是否可清除
        //$template->set_duration(BEGINTIME,ENDTIME); //设置ANDROID客户端在此时间区间内展示消息
        return $template;
    }



    //注：IOS离线推送需通过APN进行转发，需填写pushInfo字段，目前仅不支持通知弹框下载功能
    /**
     * 通知弹框下载模板
     * @param string $title 通知栏标题
     * @param string $content 通知栏内容
     * @param string $download_url 下载链接
     * @return mixed
     */
    public function IGtNotyPopLoadTemplateDemo($title,$content,$download_url){
        $template =  new \IGtNotyPopLoadTemplate();

        $template ->set_appId($this->app_id);//应用appid
        $template ->set_appkey($this->app_key);//应用appkey
        //通知栏
        $template ->set_notyTitle($title);//通知栏标题
        $template ->set_notyContent($content);//通知栏内容
        $template ->set_notyIcon("");//通知栏logo
        $template ->set_isBelled(true);//是否响铃
        $template ->set_isVibrationed(true);//是否震动
        $template ->set_isCleared(true);//通知栏是否可清除
        //弹框
        $template ->set_popTitle($title);//弹框标题
        $template ->set_popContent($content);//弹框内容
        $template ->set_popImage("");//弹框图片
        $template ->set_popButton1("下载");//左键
        $template ->set_popButton2("取消");//右键
        //下载
        $template ->set_loadIcon("");//弹框图片
        $template ->set_loadTitle(env('APP_NAME'));
        $template ->set_loadUrl($download_url);
        $template ->set_isAutoInstall(false);
        $template ->set_isActived(true);
        //$template->set_notifyStyle(0);
        //$template->set_duration(BEGINTIME,ENDTIME); //设置ANDROID客户端在此时间区间内展示消息

        return $template;
    }

    //多标签推送接口案例
    public function pushMessageByTag($title,$content){
        $igt = new \IGeTui($this->host,$this->app_key,$this->master_secret);
        $template = $this->IGtLinkTemplateDemo($title,$content);
        //个推信息体
        //基于应用消息体
        $message = new \IGtTagMessage();
        $message->set_isOffline(true);
        $message->set_offlineExpireTime(10 * 60 * 1000);//离线时间单位为毫秒，例，两个小时离线为3600*1000*2
        $message->set_data($template);

        $appIdList=array($this->app_id);

        $message->set_tag("123");
        $message->set_appIdList($appIdList);

        $rep = $igt->pushTagMessage($message);

        return $rep;
    }

}